<template>
    <view class="refund-list-main">
        <view class="refund-list-content">
            <view v-if="props.refundOrderId">
                <view class="reject-info">
                    <view class="reject-info-title">商家驳回，请重新补充信息提交申请</view>
                    <view class="reject-info-desc">*48小时未完成提交，则默认取消申请</view>
                </view>
                <view class="reject-reason">驳回原因：{{ Data.refundRejectReason }}</view>
            </view>
            <view class="goods-list">
                <view class="goods" v-for="(item, index) in goodsStore.refundGoodsList" :key="index">
                    <view v-if="!props.refundOrderId" class="goods-select" @click="selectGoodsHandler(index, item)">
                        <image
                            v-if="item.active"
                            class="img-icon"
                            :src="getImgOssUrl('/ui-prod-2.0.0/radio_active_icon_2.0.png')"></image>
                        <image
                            v-else-if="!item.num"
                            class="img-icon"
                            :src="getImgOssUrl('/ui-prod-2.0.0/radio_disabled_icon_2.0.png')"></image>
                        <image v-else class="img-icon" :src="getImgOssUrl('/ui-prod-2.0.0/radio_icon_2.0.png')"></image>
                    </view>
                    <view class="goods-img">
                        <image :src="item?.goodsImg || defaultImg"></image>
                    </view>
                    <view class="goods-info">
                        <view class="goods-name">{{ item.goodsName }}</view>
                        <view class="goods-sku">{{ getSpecValue(item) }}</view>
                        <view class="goods-btn">
                            <view class="goods-price">
                                <!-- 积分商城订单（虚拟商品暂时不支持售后） -->
                                <view v-if="Data.orderType === 6">
                                    <text v-if="item.sellPrice > 0">￥{{ floatDivide(item.sellPrice, 100) }}+</text>
                                    <text>{{ floatDivide(item.sellPoint, 100) }}积分</text>
                                </view>
                                <view v-else-if="item.sellPoint > 0">
                                    <text v-if="item.sellPrice > 0">{{ floatDivide(item.sellPrice, 100) }}元+</text>
                                    <text>{{ floatDivide(item.sellPoint, 100) }}积分</text>
                                </view>
                                <view v-else>
                                    <text>￥{{ floatDivide(item.sellPrice, 100) }}</text>
                                </view>
                            </view>
                            <!-- 若订单已经同步到ERP，且这个商品在下单时已经是ERP商品，则申请售后时，不支持选择数量，默认是【最多可售后数量】 -->
                            <view v-if="item.syncErp">x{{ item.buyNum - item.refundGoodsCount }} </view>
                            <view v-else>
                                <ShoppingGoodsSteps
                                    v-if="!props.refundOrderId"
                                    :num="item.num"
                                    :maxQuantity="item.buyNum - item.refundGoodsCount"
                                    @AddShoppingList="goodsNumHandler($event, index)" />
                                <view v-else>x{{ item.refundGoodsCount }}</view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="logistics-fee" v-if="!Data.isSelfPickup">
                    <view class="logistics-fee-left" @click="logisticsHandler">
                        <view v-if="!props.refundOrderId">
                            <image
                                v-if="logisticsDisabled"
                                class="img-icon"
                                :src="getImgOssUrl('/ui-prod-2.0.0/radio_disabled_icon_2.0.png')"></image>
                            <image
                                v-else-if="Data.logisticsChecked"
                                class="img-icon"
                                :src="getImgOssUrl('/ui-prod-2.0.0/radio_active_icon_2.0.png')"></image>
                            <image
                                v-else
                                class="img-icon"
                                :src="getImgOssUrl('/ui-prod-2.0.0/radio_icon_2.0.png')"></image>
                        </view>
                        运费
                    </view>
                    <view class="right">￥{{ floatDivide(goodsStore.refundGoodsLogisticsFee, 100) }}</view>
                </view>
            </view>
            <!--  -->
            <view class="refund-form">
                <view class="refund-cell">
                    <view class="refund-cell-label">退款类型</view>
                    <picker
                        @change="refundTypePickerChange"
                        :value="Data.refundIndex"
                        :range="checkRefundTypeList"
                        range-key="name">
                        <view class="refund-cell-text">
                            <view :class="{ 'text-placeholder': !Data.refundTypeName }">
                                {{ Data.refundTypeName ? Data.refundTypeName : '请选择' }}
                            </view>
                            <image class="img-icon" :src="getImgOssUrl('/ui-prod-2.0.0/rightarrow1.1.png')"></image>
                        </view>
                    </picker>
                </view>
                <view class="refund-cell">
                    <view class="refund-cell-label">退货理由</view>
                    <picker @change="reasonPickerChange" :value="Data.reasonIndex" :range="reasonList" range-key="name">
                        <view class="refund-cell-text">
                            <view :class="{ 'text-placeholder': !Data.reasonName }">
                                {{ Data.reasonName ? Data.reasonName : '请选择' }}
                            </view>
                            <image class="img-icon" :src="getImgOssUrl('/ui-prod-2.0.0/rightarrow1.1.png')"></image>
                        </view>
                    </picker>
                </view>
                <view class="refund-remark">
                    <view class="refund-remark-title">退货说明</view>
                    <textarea
                        class="refund-remark-text"
                        v-model="Data.description"
                        maxlength="200"
                        placeholder="补充退货说明" />
                </view>
                <view class="refund-upload">
                    <view class="refund-upload-title">上传凭证</view>
                    <view class="refund-upload-list">
                        <view class="refund-img-wrap" v-for="(item, index) in Data.imgList" :key="index">
                            <image class="refund-img" :src="item.imgUrl"></image>
                            <image
                                @click.stop="delRefundImg(index)"
                                class="refund-img-close"
                                :src="getImgOssUrl('/ui-prod-2.0.0/close_icon_2.0.png')"></image>
                        </view>
                        <view v-if="Data.imgList.length < 3" class="refund-upload-img" @click="upLoadImgHandler">
                            <image class="icon-img" :src="getImgOssUrl('/ui-prod-2.0.0/add_icon_2.0.png')"></image>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="footer">
            <view class="footer-content">
                <!-- yyy 添加全选功能？ -->
                <!-- <view>
                    <image class="img-icon" :src="getImgOssUrl('/ui-prod-2.0.0/radio_active_icon_2.0.png')"></image>
                    <image class="img-icon" :src="getImgOssUrl('/ui-prod-2.0.0/radio_disabled_icon_2.0.png')"></image>
                    <image class="img-icon" :src="getImgOssUrl('/ui-prod-2.0.0/radio_icon_2.0.png')"></image>
                    <view>全选</view>
              </view> -->
                <view class="footer-price">
                    预计可退 <text>￥{{ floatDivide(allTotal, 100) }}</text>
                    <!-- yyy 展示退回积分 -->
                    <view class="foot-price-point" v-if="allTotalPoint">
                        退回{{ floatDivide(allTotalPoint, 100) }}积分
                    </view>
                </view>
                <view class="footer-right">
                    <view class="footer-btn" v-if="props.refundOrderId" @click="cancelRefund">取消售后</view>
                    <view class="footer-btn active" @click="clickRefund">申请退款</view>
                </view>
            </view>
        </view>
        <view class="popup-dialog" v-if="Data.repealShow">
            <view class="popup-dialog-content">
                <view class="title">确认取消售后吗？</view>
                <view class="button">
                    <view class="cancel" @click="Data.repealShow = false">取消</view>
                    <view class="confirm" @click="confirmRepeal">确认</view>
                </view>
            </view>
        </view>
        <view class="popup-dialog" v-if="Data.delImgShow">
            <view class="popup-dialog-content">
                <view class="title">确认删除该图片吗？</view>
                <view class="button">
                    <view class="cancel" @click="Data.delImgShow = false">取消</view>
                    <view class="confirm" @click="delImgHandler">确认</view>
                </view>
            </view>
        </view>
        <Loading />
        <!-- 隐私监听 -->
        <el-privacy-listener-popup></el-privacy-listener-popup>
    </view>
</template>
<script setup>
import { ref, reactive, computed } from 'vue';
import { floatDivide, getImgOssUrl, getAppId } from '@/commons/utils.js';
import prenv from '@/prenv';
import request from '@/request';
import store from '@/store';
import router from '@/router';
import ShoppingGoodsSteps from '@/components/shopingGoodsSteps';
import Loading from '@/components/el-loading';
import { useTrace } from '@/commons/trace';
import subscribe from '@/commons/subscribe';

const { traceReport } = useTrace();

const props = defineProps({
    refundOrderId: {
        type: [String, Number],
        default: ''
    },
    orderId: {
        type: [String, Number],
        default: ''
    },
    backType: {
        type: Number,
        default: 2
    }
});

const goodsStore = store.useGoodsStore();

const defaultImg = ref(getImgOssUrl('/ui-prod-2.0.0/errorImg.png'));

const refundTypeList = [
    {
        name: '仅退款',
        code: 1
    },
    {
        name: '退货退款',
        code: 2
    }
];

const checkRefundTypeList = computed(() => {
    // 自提订单只有仅退款
    if (Data.isSelfPickup) {
        return refundTypeList.filter(x => x.code !== 2);
    }
    return refundTypeList;
});

const reasonList = [
    { name: '选错下单地址', code: '1' },
    { name: '商品质量问题', code: '2' },
    { name: '没收到商品', code: '3' },
    { name: '商家协商一致', code: '4' },
    { name: '物流问题', code: '5' },
    { name: '不想要了', code: '6' },
    { name: '多拍错拍', code: '7' },
    { name: '7天无理由', code: '8' },
    { name: '其他', code: '9' }
];

const Data = reactive({
    orderType: 1,
    // 是否是自提订单
    isSelfPickup: '',
    repealShow: false,
    delImgShow: false,
    delImgIndex: 0,
    refundIndex: 0,
    reasonIndex: 0,
    refundType: '',
    refundTypeName: '',
    reasonType: '',
    reasonName: '',
    logisticsFee: 0,
    logisticsChecked: false,
    imgList: [],
    description: '',
    refundRejectReason: ''
});

goodsStore.refundGoodsList.map(el => (el.num = el.buyNum - el.refundGoodsCount));

const allTotal = computed(() => {
    let amount = goodsStore.refundGoodsList.reduce((pre, cur) => {
        if (cur.active) {
            return pre + cur.sellPrice * cur.num;
        } else {
            return pre;
        }
    }, 0);
    return props.refundOrderId || Data.logisticsChecked ? amount + goodsStore.refundGoodsLogisticsFee : amount;
});

const allTotalPoint = computed(() => {
    let amount = goodsStore.refundGoodsList.reduce((pre, cur) => {
        if (cur.active) {
            return pre + cur.sellPoint * cur.num;
        } else {
            return pre;
        }
    }, 0);
    return amount;
});

const logisticsDisabled = computed(() => {
    return goodsStore.refundGoodsRefundLogisticsFee == goodsStore.refundGoodsLogisticsFee;
});

const initDetail = async () => {
    goodsStore.refundGoodsList = [];
    goodsStore.refundGoodsLogisticsFee = 0;
    let { refundOrderId } = props;
    let res = await request('refundOrderDetailServ', { refundOrderId: refundOrderId });
    let info = res.data || {};
    Data.refundRejectReason = info.refundRejectReason;
    Data.refundIndex = info.refundType - 1;
    let refundTypeInfo = refundTypeList.find(el => el.code == info.refundType) || {};
    Data.refundType = info.refundType;
    Data.refundTypeName = refundTypeInfo.name;
    Data.reasonIndex = info.reason - 1;
    Data.reasonType = info.reason;
    Data.reasonName = info.reasonCharacter;
    Data.description = info.description;
    Data.orderType = info.orderType;
    Data.isSelfPickup = Number(goodsStore.isSelfPickup);
    goodsStore.refundGoodsLogisticsFee = info.refundLogisticsFee;
    let list = [];
    info.refundGoods.map(el => {
        list.push({ ...el.goods[0], refundGoodsCount: el.refundGoodsCount });
    });
    goodsStore.refundGoodsList = list;
    goodsStore.refundGoodsList.map(el => {
        el.num = el.refundGoodsCount;
        el.active = true;
        el.sellPoint = el.goodPoints;
    });
    Data.imgList = [];
    if (info.refundProof && info.refundProof.proof) {
        for (let i in info.refundProof) {
            Data.imgList.push({
                imgUrl: info.refundProof[i]
            });
        }
    }
};
if (props.refundOrderId) {
    initDetail();
} else {
    Data.orderType = Number(goodsStore.orderType);
    Data.isSelfPickup = Number(goodsStore.isSelfPickup);
}

const selectGoodsHandler = (index, item) => {
    if (!goodsStore.refundGoodsList[index].num) return;
    goodsStore.refundGoodsList[index].active = !item.active;
};

const goodsNumHandler = (type, index) => {
    let num = goodsStore.refundGoodsList[index].num;
    let numMax = goodsStore.refundGoodsList[index].buyNum - goodsStore.refundGoodsList[index].refundGoodsCount;
    if (type == 2) {
        if (num <= 1) return;
        goodsStore.refundGoodsList[index].num = num - 1;
    } else if (type == 1) {
        if (num == numMax) return;
        goodsStore.refundGoodsList[index].num = num + 1;
    }
};

const logisticsHandler = () => {
    if (logisticsDisabled.value) return;
    Data.logisticsChecked = !Data.logisticsChecked;
};

const refundTypePickerChange = e => {
    let index = e.detail.value;
    Data.refundIndex = index;
    Data.refundTypeName = refundTypeList[index].name;
    Data.refundType = refundTypeList[index].code;
};

const reasonPickerChange = e => {
    let index = e.detail.value;
    Data.reasonIndex = index;
    Data.reasonName = reasonList[index].name;
    Data.reasonType = reasonList[index].code;
};

const delRefundImg = index => {
    Data.delImgIndex = index;
    Data.delImgShow = true;
};

const delImgHandler = () => {
    Data.imgList.splice(Data.delImgIndex, 1);
    Data.delImgShow = false;
};

const upLoadImgHandler = () => {
    if (Data.imgList.length > 2) return;
    uni.chooseImage({
        count: 3,
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera '], //从相册选择
        success: function (res) {
            const tempFilePaths = res.tempFilePaths;
            const currentEnv = store.useEnvStore().currentEnv;
            const url = prenv[currentEnv]['API_BASE_URL']['apigw'] + '/miniapp/file/upload';
            tempFilePaths.map(el => {
                uni.uploadFile({
                    url: url,
                    filePath: el,
                    name: 'file',
                    header: {
                        token: uni.getStorageSync('token') || '',
                        'ZW-APP-ID': getAppId(),
                        'ZW-SHOP-ID': uni.getStorageSync('ZW_SHOP_ID') || '',
                        'ZW-TENANT-ID': uni.getStorageSync('ZW_TENANT_ID') || '',
                        'ZW-CORP-ID': uni.getStorageSync('ZW_CORP_ID') || ''
                    },
                    formData: {},
                    success: uploadFileRes => {
                        let resFile = JSON.parse(uploadFileRes.data);
                        Data.imgList.push({
                            imgUrl: resFile.data.url
                        });
                    }
                });
            });
        }
    });
};

const cancelRefund = () => {
    Data.repealShow = true;
};

const confirmRepeal = async () => {
    let params = {
        refundOrderId: props.refundOrderId
    };
    let res = await request('refundOrderRepealServ', params);
    if (res.data) {
        Data.repealShow = false;
        uni.showToast({
            title: '取消成功',
            icon: 'none'
        });
        router.redirectTo({
            url: `/pages-user/orderdetail/index?orderId=${props.orderId}`
        });
    }
};

const checked = () => {
    if (!Data.refundType) {
        uni.showToast({
            title: '请选择退款类型',
            icon: 'none'
        });
        return false;
    } else if (!Data.reasonType) {
        uni.showToast({
            title: '请选择退货理由',
            icon: 'none'
        });
        return false;
    } else {
        return true;
    }
};

const clickRefund = async () => {
    if (!checked()) return;
    if (props.refundOrderId) {
        refundSupplement();
        return;
    }
    let refundGoods = [];
    goodsStore.refundGoodsList.map(el => {
        if (el.active) {
            refundGoods.push({
                goodsId: el.goodsId,
                goodsName: el.goodsName,
                skuId: el.skuId,
                orderGoodsId: el.id,
                refundGoodsCount: el.num
            });
        }
    });
    if (!refundGoods.length) {
        uni.showToast({
            title: '请勾选商品',
            icon: 'none'
        });
        return;
    }
    let refundProof = Data.imgList.length
        ? {
              proof: Data.imgList[0]?.imgUrl,
              proof2: Data.imgList[1]?.imgUrl,
              proof3: Data.imgList[2]?.imgUrl
          }
        : undefined;
    let params = {
        orderId: props.orderId,
        refundLogisticsFee: Data.logisticsChecked ? goodsStore.refundGoodsLogisticsFee : 0,
        refundType: Data.refundType,
        reason: Data.reasonType,
        description: Data.description,
        refundProof: refundProof,
        refundGoods: refundGoods
    };
    await subscribe('order_wait_review');
    /****************申请退款埋点代码开始**************************/
    const traceGoodsList = [];
    refundGoods.map(item => {
        traceGoodsList.push({
            productId: item.goodsId,
            productName: item.goodsName,
            skuId: item.skuId,
            returnNumber: item.refundGoodsCount
        });
    });
    traceReport('return_goods', {
        orderId: props.orderId,
        goods: traceGoodsList
    });
    /****************申请退款埋点代码结束**************************/
    let res = await request('refundOrderApplyServ', params);
    if (res.data) {
        uni.showToast({
            title: '申请成功',
            icon: 'none'
        });
        router.push({
            path: '/pages-user/refunddetail/index',
            query: {
                orderId: res.data,
                backType: props.backType
            }
        });
    }
};

const refundSupplement = async () => {
    let refundProof = Data.imgList.length
        ? {
              proof: Data.imgList[0]?.imgUrl,
              proof2: Data.imgList[1]?.imgUrl,
              proof3: Data.imgList[2]?.imgUrl
          }
        : undefined;
    let params = {
        refundOrderId: props.refundOrderId,
        refundType: Data.refundType,
        reason: Data.reasonType,
        description: Data.description,
        refundProof: refundProof
    };
    let res = await request('refundOrderSupplementServ', params);
    if (res.data) {
        router.push({
            path: '/pages-user/refunddetail/index',
            query: {
                orderId: props.refundOrderId,
                backType: 2
            }
        });
    }
};

const getSpecValue = val => {
    let ary = [];
    let str = '';
    val.skuExtInfo &&
        val.skuExtInfo.map(el => {
            ary.push(el.attributeValue);
        });
    str = ary.join(';');
    return str;
};
</script>
<style lang="scss" scoped src="./index.scss"></style>
